package reflection;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author DCSGO
 * @version 1.0
 * 反射调用对象的方法
 */
public class ReflectionInvokeMethod {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Class<?> catCls = Class.forName("reflection.Cat");
        //1.调用 public 方法
        //getMethod(String name, Class<?>... parameterTypes)
        //name->方法名 parameterTypes->参数的Class对象
        Method say = catCls.getMethod("say", String.class);
        Object cat = catCls.newInstance();
        //invoke(Object obj, Object... args)
        //obj->调用该方法的Class对象 args->参数
        say.invoke(cat, "我会说话哦");//我会说话哦

        //2.调用非 public 方法
        Method sum = catCls.getDeclaredMethod("sum", int.class, double.class);
        sum.setAccessible(true);//爆破
        Object reVal = sum.invoke(cat, 100, 3.14);//返回均为 Object
        System.out.println(reVal);//103.14
        //由于 sum 方法是静态方法所以也可以将 name 置为 null
        Object reVal2 = sum.invoke(null, 666, 8.88);
        System.out.println(reVal2);//674.88
    }
}

class Cat {
    public void say(String content) {
        System.out.println(content);
    }

    private static double sum(int num1, double num2) {
        return num1 + num2;
    }
}
